package com.lb.controller;

import com.lb.common.Result;
import com.lb.entity.Order;
import com.lb.entity.OrderVO1;
import com.lb.entity.VO.OrderVo;
import com.lb.entity.VO.ShopVo;
import com.lb.entity.orderItem;
import com.lb.service.OrderItemService;
import com.lb.service.OrderService;
import com.lb.service.ShopService;
import com.lb.utils.RandomId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RequestMapping
@RestController
@CrossOrigin
@Slf4j
public class ordercontroller {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private ShopService shopService;
    @GetMapping("/order/shop")
    @Transactional
    public Result<OrderVo> order(@RequestParam String username) {
        double totalSum = 0.0;
        String no = RandomId.generateUUID();
        List<ShopVo> list = shopService.get(username);
         List<orderItem>  list1 = new ArrayList<>();
        for (ShopVo shopVo : list) {
            orderItem orderItem = new orderItem();
          Double result=  shopVo.getPrice()*shopVo.getNumber();
          // BeanUtils.copyProperties(shopVo, orderItem);
            orderItem.setNumber(shopVo.getNumber());
            orderItem.setPrice(shopVo.getPrice());
            orderItem.setDishId(shopVo.getDishId());
            orderItem.setOrderId(no);
            list1.add(orderItem);
            totalSum += result;
       }
       orderItemService.saveBatch(list1);
        Order order = new Order();
        order.setOrderNo(no);
        order.setStatus("未支付");
        order.setUserName(username);
        order.setTotalAmount(totalSum);
        order.setOrderId(0L);
        order.setCreatedTime(LocalDateTime.now());
       //orderItemService.add(list1);
        orderService.save(order);
        return Result.success();
    }

    @GetMapping("/order/getByusername")
    public Result getOrder(@RequestParam String username){
   List<OrderVO1> result= orderService.get(username);
   return Result.success(result);
    }
}
